﻿using Newtonsoft.Json;
using System;
using System.Windows.Forms;

namespace EasyIot.WinApp
{
    public partial class frmAdmin : SystemForm
    {
        static bool serial_init = false;
        static bool socket_init = false;

        public frmAdmin()
        {
            InitializeComponent();
        }

        public override void ShowForm(RedirectType eType = RedirectType.Redirect_Next, object oParam = null)
        {
            base.ShowForm(); 
        }

        private void btnBack_Click(object sender, EventArgs e)
        {
           OnEventShowForm(FormCase.Form_StandBy);
        } 

        private void btnDownload_Click(object sender, EventArgs e)
        { 
            string url = DataMgr.ApiUrl + "Download";
            string data = "select * from device"; string content = DESEncrypt.Encrypt(data); string input = "{\"content\":\"" + content + "\"}";
            PostResult response = PostHelper.HttpPost(url, input); string output = JsonConvert.SerializeObject(response);
            AddMessage("Http下载:" + url + " 输入,加密前:" + data + ",DES加密后:" + input + " 输出:" + output);
        }  

        private void btnUpLoad_Click(object sender, EventArgs e)
        {
            string url = DataMgr.ApiUrl + "UpLoad";
            string data = "update device set LastActive='" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "' where DeviceCode='1001'"; string content = DESEncrypt.Encrypt(data); string input = "{\"content\":\"" + content + "\"}";
            PostResult response = PostHelper.HttpPost(url, input); string output = JsonConvert.SerializeObject(response);
            AddMessage("Http上传:" + url + " 输入,加密前:" + data + ",DES加密后:" + input + " 输出:" + output);
        }

        private void btnSerial_Click(object sender, EventArgs e)
        {
            AddMessage("串口测试");

            // 串口初始化
            if (!serial_init)
            {
                serial_init = true;
                DataMgr.LockSP.OpenSerialPort(DataMgr.Serial_Lock);
            }

            string errmsg = string.Empty;

            DataMgr.Open(0, 1, ref errmsg);
        }


        private void btnSocket_Click(object sender, EventArgs e)
        {
            AddMessage("Socket测试");

            // 网络初始化
            if (!socket_init)
            {
                socket_init = true;
                TcpClientMgr.Start(DataMgr.ServerIP, DataMgr.ServerPort);
            } 
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            Environment.Exit(0);
        }

        public void AddMessage(string msg)
        {
            if (IsDisposed) return;

            this.BeginInvoke((EventHandler)(delegate
            {
                if (rtbMsg.Lines.Length > 15)
                {
                    rtbMsg.Clear();
                }
                rtbMsg.AppendText(DateTime.Now.ToString("yy-MM-dd HH:mm:ss") + " " + msg + "\r\n");
                Application.DoEvents();
            }));
        } 
    }
}
